package Day2025_02_26;

import java.util.Random;

public class LeetCode215 {
    public int findKthLargest(int[] nums, int k) {
        return partition(nums, 0, nums.length - 1, k);
    }

    private static int partition (int[] nums, int left, int right, int k) {
        int target = nums[new Random().nextInt(right - left + 1) + left];
        int l = left - 1, r = right + 1, i = left;
        while (i < r) {
            if (nums[i] > target) swap(nums, i++, ++l);
            else if (nums[i] < target) swap(nums, i, --r);
            else i++;
        }
        //[left, l][l + 1, r - 1][r, right]
        int a = l - left + 1, b = r - l - 1, c = right - r + 1;
        if (k <= a) return partition(nums, left, l, k);
        else if (k > a + b) return partition(nums, r, right, k - a - b);
        else return target;
    }

    private static void swap(int[] nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
}
